package com.kedacom.freedomLabel.printer;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.lzscale.scalelib.misclib.PrintStatusCallback;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class ScalePrinter<T> {

    protected static final String LINE_BREAK = "\r\n";
    protected ExecutorService printThread = Executors.newSingleThreadExecutor();
    protected boolean isReprint;

    public abstract void print(@NonNull T info, @Nullable PrintStatusCallback callBack);

    protected String getCenterStr(String txt, boolean isBig) {
        if (isBig)
            return getCenterStr(txt, 16);
        return getCenterStr(txt, 32);
    }

    protected String getCenterStr(String txt, int maxByteLen) {
        StringBuilder res = new StringBuilder();
        String spaceChar = " ";
        do {
            int len = getSingleByteCount(txt);
            if (len <= maxByteLen) {
                for (int i = 0; i < (maxByteLen - len) / 2; i++) {
                    res.insert(0, spaceChar);
                }
                res.append(txt);
                break;
            }
            String str = getStrByByteCount(txt, maxByteLen);
            res.append(str).append("\r\n");
            txt = txt.substring(str.length());
        } while (true);
        return res.toString();
    }

    protected int getSingleByteCount(String txt) {
        char[] arr = txt.toCharArray();
        int i = 0, count = 0;
        for (; i < arr.length; i++) {
            if (arr[i] > 256)
                count += 2;
            else
                count++;
        }
        return count;
    }

    protected String getStrByByteCount(String txt, int byteCount) {
        char[] arr = txt.toCharArray();
        int i = 0, count = 0;
        for (; i < arr.length; i++) {
            if (arr[i] > 256)
                count += 2;
            else
                count++;
            if (count == byteCount)
                return txt.substring(0, i + 1);
            else if (count > byteCount)
                return txt.substring(0, i);
        }
        return txt;
    }
}
